using System;
using System.Drawing;
using System.Drawing.Printing;
using System.Drawing.Text;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using System.Xml;
using HWEngine;
using HWEngine.Configuration;
using HWEngine.Generators;
using HWEngine.Tools;
using System.Collections.Generic;

namespace HandWriter
{
	public partial class MainWindow : Form
	{
		private LetterSetRepository _fonts;
		private IDocument _activeDoc;

		[DllImport("WinAPI_Helper.dll")]
		public static extern bool SendMouseEvent(int e, int X, int Y);

		public MainWindow()
		{
			InitializeComponent();

			//load fonts
			_fonts = new LetterSetRepository(Path.Combine(Application.StartupPath, "Fonts"));

			Left = Config.Configuration.MainFormLeft;
			Top = Config.Configuration.MainFormTop;
			Width = Config.Configuration.MainFormWidth;
			Height = Config.Configuration.MainFormHeight;

			AddNewTab();
		}

		private void MainForm_Load(object sender, EventArgs e)
		{
			
		}

		private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
		{
			Config.Configuration.MainFormLeft = Left;
			Config.Configuration.MainFormTop = Top;
			Config.Configuration.MainFormWidth = Width;
			Config.Configuration.MainFormHeight = Height;
			Config.Configuration.SaveConfig();
		}

		private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
		{
			if (e.CloseReason == CloseReason.UserClosing)
			{
				DialogResult res =
					MessageBox.Show("Application is closing. Do you wanna save changes in font?", "Hand Writer",
									MessageBoxButtons.YesNoCancel,
									MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);

				if (res == DialogResult.Yes)
				{
					_fonts.Save();
				}
				if (res == DialogResult.Cancel)
				{
					e.Cancel = true;
				}
			}
		}

		/// <summary>
		/// Tweaks the tabs looks like in VS2008
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void tabDocuments_GetTabRegion(object sender, MdiTabControl.TabControl.GetTabRegionEventArgs e)
		{
			e.Points[1] = new Point(e.TabHeight - 2, 2);
			e.Points[2] = new Point(e.TabHeight + 2, 0);
		}

		private void AddNewTab()
		{
			Form f = new DocumentEditorDialog(_fonts);
			f.Text = "New Document";
			tabDocuments.TabPages.Add(f);
		}

		private void newToolStripMenuItem1_Click(object sender, EventArgs e)
		{
			AddNewTab();
		}

		private void fontManagerToolStripMenuItem_Click(object sender, EventArgs e)
		{
			Form f = new FontsManagerDialog(_fonts);
			f.Text = "Fonts Manager";
			tabDocuments.TabPages.Add(f);
		}

		private void exitToolStripMenuItem_Click(object sender, EventArgs e)
		{
			Close();
		}

		#region Not implemented handlers

		private void openToolStripMenuItem1_Click(object sender, EventArgs e)
		{
			MessageBox.Show("Not implemented yet");
		}

		private void saveToolStripMenuItem_Click(object sender, EventArgs e)
		{
			if (_activeDoc != null)
			{
				_activeDoc.Save();
			}
		}

		private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
		{
			if (_activeDoc != null)
			{
				_activeDoc.SaveAs();
			}
		}

		private void saveAllToolStripMenuItem_Click(object sender, EventArgs e)
		{
			if (_activeDoc != null)
			{
				_activeDoc.SaveAll();
			}
		}

		private void printToolStripMenuItem_Click(object sender, EventArgs e)
		{
			if (_activeDoc != null)
			{
				_activeDoc.Print();
			}
		}

		private void optionsToolStripMenuItem_Click(object sender, EventArgs e)
		{
			MessageBox.Show("Not implemented yet");
		}

		private void contentsToolStripMenuItem_Click(object sender, EventArgs e)
		{
			MessageBox.Show("Not implemented yet");
		}

		private void indexToolStripMenuItem_Click(object sender, EventArgs e)
		{
			MessageBox.Show("Not implemented yet");
		}

		private void searchToolStripMenuItem_Click(object sender, EventArgs e)
		{
			MessageBox.Show("Not implemented yet");
		}

		private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
		{
			MessageBox.Show("Not implemented yet");
		}

		private void exportToolStripMenuItem_Click(object sender, EventArgs e)
		{
			if (_activeDoc != null)
			{
				_activeDoc.Export();
			}
		}

		#endregion

		private void tabDocuments_TabIndexChanged(object sender, EventArgs e)
		{
		
		}

		private void tabDocuments_TabSelected(object sender, EventArgs e)
		{
			UpdateTopMenu();
		}

		private void UpdateTopMenu()
		{
			printToolStripMenuItem.Enabled = false;
			saveToolStripMenuItem.Enabled = false;
			saveAsToolStripMenuItem.Enabled = false;
			saveAllToolStripMenuItem.Enabled = false;
			exportToolStripMenuItem.Enabled = false;

			_activeDoc = tabDocuments.SelectedForm as IDocument;
			if (_activeDoc != null)
			{
				printToolStripMenuItem.Enabled = _activeDoc.PrintingAllowed;
				saveToolStripMenuItem.Enabled = _activeDoc.SaveAllowed;
				saveAllToolStripMenuItem.Enabled = _activeDoc.SaveAllAllowed;
				saveAsToolStripMenuItem.Enabled = _activeDoc.SaveAsAllowed;
				exportToolStripMenuItem.Enabled = _activeDoc.ExportAllowed;
			}
		}

		/*
		private void mouseActionToolStripMenuItem_Click(object sender, EventArgs e)
		{
			_needToBreakAction = false;
			var tf = new TimerForm(10, delegate
			{
				DrawingMode oldMode = HWGenerator.CurrentLetterSet.DrawingMode;
				HWGenerator.CurrentLetterSet.DrawingMode = DrawingMode.CustomPointsDelegate;
				Line.PaintEvent = delegate(PaintEventArguments args, PointF position)
				{
					int x = _currentMousePos.X + (int)Math.Round(position.X);
					int y = _currentMousePos.Y + (int)Math.Round(position.Y);

					x = (int) Math.Round(((double)x / Screen.PrimaryScreen.Bounds.Width) * 0xffff);
					y = (int) Math.Round(((double)y / Screen.PrimaryScreen.Bounds.Height) * 0xffff);

					switch (args)
					{
						case PaintEventArguments.Start:
							{
								SendMouseEvent(2, x, y);
								SendMouseEvent(0, x, y);
							}
							break;
						case PaintEventArguments.End:
							{
								SendMouseEvent(1, x, y);
							}
							break;
						case PaintEventArguments.Point:
							{
								SendMouseEvent(2, x, y);
							}
							break;
					}
					Thread.Sleep(1);
					Application.DoEvents();

					if (_needToBreakAction)
					{
						HWGenerator.CurrentLetterSet.DrawingMode = oldMode;
						Line.PaintEvent = null;
						_needToBreakAction = false;
						SendMouseEvent(1, x, y); // Set mouse up
					}
				};
				Generate();
				Line.PaintEvent = null;
				HWGenerator.CurrentLetterSet.DrawingMode = oldMode;
			});
			tf.Show();
		}

		private void WriteExportContent(TextWriter tw)
		{
			DrawingMode oldMode = HWGenerator.CurrentLetterSet.DrawingMode;
			HWGenerator.CurrentLetterSet.DrawingMode = DrawingMode.CustomPointsDelegate;
			Line.PaintEvent = delegate(PaintEventArguments args, PointF position)
			{
				var x = (int)Math.Round(position.X);
				var y = (int)Math.Round(position.Y);

				switch (args)
				{
					case PaintEventArguments.Start:
						{
							tw.WriteLine("S:{0},{1}", x, y);
						}
						break;
					case PaintEventArguments.End:
						{
							tw.WriteLine("E:{0},{1}", x, y);
							tw.WriteLine();
						}
						break;
					case PaintEventArguments.Point:
						{
							tw.WriteLine("M:{0},{1}", x, y);
						}
						break;
				}
			};
			Generate();
			Line.PaintEvent = null;
			HWGenerator.CurrentLetterSet.DrawingMode = oldMode;
		}

		private void exportToolStripMenuItem_Click(object sender, EventArgs e)
		{
			if (saveFileDialog2.ShowDialog() == DialogResult.OK)
			{
				using (var sw = new StreamWriter(saveFileDialog2.FileName))
				{
					WriteExportContent(sw);
				}
			}
		}

		private void breakExecutionToolStripMenuItem1_Click(object sender, EventArgs e)
		{
			_needToBreakAction = true;
		}

		private void makeExecutivePresentationToolStripMenuItem1_Click(object sender, EventArgs e)
		{
			var po = new PresentationOptions();
			if (po.ShowDialog() == DialogResult.OK)
			{
				if (saveFileDialog2.ShowDialog() == DialogResult.OK)
				{
					string srcPath = Path.Combine(Application.StartupPath, @"Templates\MadMouse.exe");
					File.Copy(srcPath, saveFileDialog2.FileName);
					var sb = new StringBuilder();
					var sw = new StringWriter(sb);
					WriteExportContent(sw);
					sw.Flush();
					sb.Insert(0, po.Result);
					IntPtr h = Resources.BeginUpdateResource(saveFileDialog2.FileName, false);
					byte[] data = Encoding.ASCII.GetBytes(sb.ToString());
					Resources.UpdateResource(h, (IntPtr) 10, "MYDATA", 0, data, data.Length);
					Resources.EndUpdateResource(h, false);
				}
			}
		}

		private void systemHotkey1_Pressed(object sender, EventArgs e)
		{
			_needToBreakAction = true;
		}

		private void btnSaveText_Click(object sender, EventArgs e)
		{
			if (saveFileText.ShowDialog() == DialogResult.OK)
			{
				edUserInput.SaveFile(saveFileText.FileName);
			}
		}

		private void btnLoadText_Click(object sender, EventArgs e)
		{
			if (openFileText.ShowDialog() == DialogResult.OK)
			{
				edUserInput.LoadFile(openFileText.FileName);
			}
		}

		private void saveToolStripMenuItem_Click(object sender, EventArgs e)
		{
			_fonts.Save();
		}

		private void fontsSelectionList_OnFontItemSelected(object sender, EventArgs e)
		{
			FontEditor fe = new FontEditor(_fonts.Get(fontsSelectionList.SelectedFontName));
			fe.ShowDialog();
		}
		 * 
		*/
	}
}